package com.mychat.controller;

import com.mychat.annotation.GlobalInterceptor;
import com.mychat.entity.Constants;
import com.mychat.entity.config.AppConfig;
import com.mychat.entity.po.AppUpdate;
import com.mychat.entity.query.AppUpdateQuery;
import com.mychat.entity.vo.AppUpdateVO;
import com.mychat.entity.vo.ResponseVO;
import com.mychat.enums.AppUpdateFileTypeEnum;
import com.mychat.enums.AppUpdateStatusEnum;
import com.mychat.exception.BusinessException;
import com.mychat.service.AppUpdateService;
import com.mychat.utils.CopyTools;
import com.mychat.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

@RestController
@RequestMapping("/update")
public class UpdateController extends ABaseController {
    @Resource
    private AppUpdateService appUpdateService;
    @Resource
    private AppConfig appConfig;


    @RequestMapping("/checkVersion")
    @GlobalInterceptor
    public ResponseVO checkVersion(String appVersion, String uid) {
        if (StringUtils.isEmpty(appVersion)) {
            return getSuccessResponseVO(null);
        }
        AppUpdate appUpdate = this.appUpdateService.getLatestUpdate(appVersion, uid);
        if (appUpdate == null) {
            return getSuccessResponseVO(null);
        }

        AppUpdateVO appUpdateVO = CopyTools.copy(appUpdate, AppUpdateVO.class);
        if (AppUpdateFileTypeEnum.LOCAL.getType().equals(appUpdate.getFileType())) {
            File file = new File(appConfig.getProjectFolder() + Constants.APP_UPDATE_FOLDER + appUpdate.getId() + Constants.APP_EXE_SUFFIX);
            appUpdateVO.setSize(file.length());
        } else {
            appUpdateVO.setSize(0L);
        }
        appUpdateVO.setUpdateList(Arrays.asList(appUpdate.getUpdateDescArray()));
        String fileName = Constants.APP_NAME + appUpdate.getVersion() + Constants.APP_EXE_SUFFIX;
        appUpdateVO.setFileName(fileName);
        return getSuccessResponseVO(appUpdateVO);
    }


}
